package p3as.cliente;

import java.util.ArrayList;
import java.util.concurrent.Semaphore;
import java.util.logging.Level;
import java.util.logging.Logger;

public class AnimationController extends Thread{
    
    private Semaphore mutex;
    private ArrayList<Ball> ballList;
    private Scene scene;
    private Score score;
    private Principal principal;
    private int i = 1;

    public AnimationController(Scene scene, Score score, Principal principal) {
        this.scene = scene;
        this.score = score;
        this.principal = principal;
        this.mutex = new Semaphore(1);
        ballList = new ArrayList();
        inicializarBallList();
    }
    
    @Override
    public void run(){   
            while(true){
                try {
                    mutex.acquire();
                    for (Ball b : ballList) {
                    score.setScore(score.getScore()+scene.collision(b)); //Le suma el resultado al score
                    principal.getScoreText().setText(String.valueOf(score.getScore()));
                    b.move();
                    }
                    mutex.release();
                try {
                    Thread.sleep(5);
                } catch (InterruptedException ex) {
                    Logger.getLogger(AnimationController.class.getName()).log(Level.SEVERE, null, ex);
                }
               
            } catch (InterruptedException ex) {
                    Logger.getLogger(AnimationController.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
    }
    
    public void createBall(int x, int y){
        
        try {
            Ball ball = new Ball(x,y,1,1);
            
            if((i % 2) == 0) {
                ball.setDx(ball.getDx()*(-1));
            }
            i++;
            mutex.acquire();
            ballList.add(ball);
            scene.addChild(ball);
            mutex.release();
        } catch (InterruptedException ex2) {
            Logger.getLogger(AnimationController.class.getName()).log(Level.SEVERE, null, ex2);
        }
    }

    public void setBallList(ArrayList<Ball> ballList) {
        synchronized(ballList){
            this.ballList = ballList;
        }
    }

    void setScene(Scene auxScene) {
        synchronized(auxScene){
            this.scene = auxScene;
        }
    }

    Drawable getScene() {
        return scene;
    }

    private void inicializarBallList() {
        for(int i=0; i < scene.getSize(); i++){
            if(scene.getChild(i) instanceof Ball){
                ballList.add((Ball) scene.getChild(i));
            }
        }
    }
    
}
